package com.example.teadoctor;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.components.XAxis.XAxisPosition;

import java.util.ArrayList;
import java.util.List;

public class DataFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.page_data,container,false);
        // 初始化饼图控件
        PieChart pieChart = view.findViewById(R.id.pie_chart);
        pieChart.setUsePercentValues(true);
        pieChart.getDescription().setEnabled(false);

// 初始化柱状图控件
        BarChart barChart = view.findViewById(R.id.bar_chart);
        barChart.getDescription().setEnabled(false);

// 加载饼图数据
        List<PieEntry> pieEntries = new ArrayList<>();
        pieEntries.add(new PieEntry(30f, "绿茶"));
        pieEntries.add(new PieEntry(25f, "红茶"));
        pieEntries.add(new PieEntry(20f, "乌龙茶"));
        pieEntries.add(new PieEntry(15f, "花茶"));
        pieEntries.add(new PieEntry(10f, "黑茶"));

        PieDataSet pieDataSet = new PieDataSet(pieEntries, "茶叶销售占比");
        pieDataSet.setColors(ColorTemplate.COLORFUL_COLORS);
        PieData pieData = new PieData(pieDataSet);
        pieChart.setData(pieData);
        pieChart.invalidate();

// 加载柱状图数据
        List<BarEntry> barEntries = new ArrayList<>();
        barEntries.add(new BarEntry(0f, 30f));
        barEntries.add(new BarEntry(1f, 25f));
        barEntries.add(new BarEntry(2f, 20f));
        barEntries.add(new BarEntry(3f, 15f));
        barEntries.add(new BarEntry(4f, 10f));

        BarDataSet barDataSet = new BarDataSet(barEntries, "茶叶销售量");
        barDataSet.setColors(ColorTemplate.COLORFUL_COLORS);
        BarData barData = new BarData(barDataSet);

        XAxis xAxis = barChart.getXAxis();
        xAxis.setValueFormatter(new IndexAxisValueFormatter(new String[]{"绿茶", "红茶", "乌龙茶", "花茶", "黑茶"}));
        xAxis.setGranularity(1f);
        xAxis.setPosition(XAxisPosition.BOTTOM);

        barChart.setData(barData);
        barChart.setFitBars(true);
        barChart.invalidate();
        return view;
    }
}
